package org.ponly.uno4j.support;

import org.ponly.common.util.IOUtils;
import org.ponly.common.util.StringUtils;
import org.ponly.web.servlet.ResourceServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 */
public class ApiServlet extends ResourceServlet {

    public ApiServlet(String resourcePath) {
        super(resourcePath);
    }

    /*-
    callback(md5) {
     create md5, title,ext  --> {docid: 123, md5: 123, title: 123}
    }

    preupload?md5=123
if not {
    upload {
         oncompile: callback
    }
}
     */
    @Override
    protected void handleRequest(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
        // 预上传
        if ("preupload".equals(path)) {
            String md5 = request.getParameter("md5");
            // if not exists
            return;
        }
        */

        // 上传
        if ("upload".equals(path)) {

            // return md5;
        }

        // 否则为获取内容
        InputStream in = getAsStream(path);
        if (null != in) {
            String rcd = request.getParameter("response-content-disposition");
            String rct = request.getParameter("response-content-type");

            if (StringUtils.hasText(rcd)) {
                rct = StringUtils.hasText(rct) ? rct : "application/octet-stream";
                response.setHeader("Content-Disposition", rcd);
            }
            if (StringUtils.hasText(rct)) {
                response.setHeader("Content-Type", rct);
            }

            IOUtils.flow(in, response.getOutputStream(), true, false);
            return;
        }
        response.sendError(404, "Resource Not Found");
    }

    protected InputStream getAsStream(String md5) {
        return null;
    }

}
